package com.app.service;

import com.app.model.main.MessageRecord;
import com.app.repository.interfaces.MessageRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by Lichaojie on 2017/5/7. It's a beautiful day.
 */
@Service
public class MessageRecordService {

    @Autowired
    private MessageRecordMapper messageRecordMapper;


    public int getMessageTimesByDay(int days,long userId){
        List<String> dayList = new ArrayList<>();

        long now = System.currentTimeMillis();
        Calendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(now);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        String dateString = "" + year + (month < 10 ? "0" + month : month) + (date < 10 ? "0" + date : date);
        dayList.add(dateString);

        long mTime = now;
        for (int i = 0; i < days - 1; i ++){
            mTime = mTime - 24 * 60 * 60 * 1000;
            Calendar calendar1 = new GregorianCalendar();
            calendar1.setTimeInMillis(mTime);
            int year1 = calendar.get(Calendar.YEAR);
            int month1 = calendar.get(Calendar.MONTH) + 1;
            int date1 = calendar.get(Calendar.DATE);
            String dateString1 = "" + year1 + (month1 < 10 ? "0" + month1 : month1) + (date1 < 10 ? "0" + date1 : date1);
            dayList.add(dateString1);
        }

        List<MessageRecord> list1 = messageRecordMapper.selectByReceiverId(userId);
        List<MessageRecord> list2 = messageRecordMapper.selectBySenderId(userId);

        List<String> sList = new ArrayList<>();

        if(list1 != null){
            for (MessageRecord messageRecord : list1){
                sList.add(messageRecord.getTime());
            }
        }
        if(list2 != null){
            for (MessageRecord messageRecord : list2){
                sList.add(messageRecord.getTime());
            }
        }

        int num = 0;
        for (String s : sList){
            if(dayList.contains(s)){
                num ++;
            }
        }

        return num;
    }
}
